package me.boot.web.common.template.controller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.google.common.collect.Lists;
import io.swagger.annotations.ApiOperation;
import me.boot.db.mybatis.template.SuperService;
import me.boot.db.mybatis.template.entity.Entity;
import me.boot.web.common.template.model.Result;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.Serializable;
import java.util.List;

public interface SaveController<
        ID extends Serializable,
        PO extends Entity<ID>,
        S extends SuperService<ID, PO>,
        DTO>
        extends BaseController<ID, PO, S> {

    @ApiOperation(value = "新增")
    @ApiOperationSupport(order = 1)
    @PostMapping(value = "/save")
    default Result<ID> save(@RequestBody @Validated DTO saveDTO) {
        PO po = fromSaveDTO(saveDTO);
        ID id = getService().insert(po);
        return id != null ? Result.newSuccess(id) : Result.newFaild("新增失败");
    }


    @ApiOperation(value = "批量新增")
    @ApiOperationSupport(order = 2)
    @PostMapping(value = "/save/batch")
    default Result<Boolean> save(@RequestBody @Validated List<DTO> saveDTOS) {
        List<PO> pos = Lists.newArrayList();
        saveDTOS.forEach(dto -> pos.add(fromSaveDTO(dto)));
        return Result.newSuccess(getService().saveBatch(pos));
    }

    default PO fromSaveDTO(DTO saveDTO) {
        return dtoToPo(saveDTO);
    }
}
